package com.mpgame.handler;

import com.mpgame.connection.ChannelRegistry;
import com.mpgame.database.redis.utils.TokenUtil;

import java.util.concurrent.TimeUnit;

import com.mpgame.common.manager.HandlerMgr;
import com.mpgame.common.proto.*;
import com.mpgame.common.utils.Log;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.ChannelHandler.Sharable;

@Sharable
public class GatewayClientHandler extends SimpleChannelInboundHandler<GamePacket>{
    private final HandlerMgr handlerMgr;

    public GatewayClientHandler(HandlerMgr handlerMgr){
        this.handlerMgr = handlerMgr;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx){
        ChannelRegistry.add(ctx.channel());
        Log.info("收到客户端连接，需在 " + TokenUtil.TOKEN_TIMEOUT + " 秒内完成Token验证，当前在线：" + ChannelRegistry.size());

        ctx.channel().eventLoop().schedule(() -> {
            boolean authenticated = ChannelRegistry.getAuthenticated(ctx.channel());
            if(!authenticated && ctx.channel().isActive()){
                Log.warn("客户端Token认证超时，关闭连接...");
                GamePacket grsp = GamePacket.newBuilder()
                    .setCmd(CmdId.GAME_AUTH_RSP)
                    .setEc(ErrorCode.AUTH_TIMEOUT)
                    .setData(ErrMsg.newBuilder().setErrMsg("Token验证超时").build().toByteString())
                    .build();
                ctx.writeAndFlush(grsp);
                ctx.channel().close();
            }
        }, TokenUtil.TOKEN_TIMEOUT, TimeUnit.SECONDS);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        ChannelRegistry.remove(ctx.channel());
        Log.info("客户端断开，当前在线：" + ChannelRegistry.size());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GamePacket pkt){
        Log.warn("收到客户端发包" + pkt);
        handlerMgr.handle(ctx, pkt);
    }
}
